//
// Created by 86136 on 2024/12/2.
//
#include "friendmodel.hpp"
#include "db.h"

using namespace std;

// 添加好友关系
void FriendModel::insert(int userid, int friendid) {
    // 组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "insert into friend values(%d, %d)", userid, friendid);
    MySQL mysql;
    if (mysql.connect()) {
        mysql.update(sql);
    }
}

// 返回用户好友列表
vector<User> FriendModel::query(int userid) {
    // 组装sql语句
    char sql[1024] = {0};
    // 对friend和user表作联合查询
    sprintf(sql, "select a.id, a.name, a.state from user a "
                 "inner join friend b on b.friendid = a.id where b.userid=%d", userid);

    vector<User> vec;

    MySQL mysql;
    if (mysql.connect()) {
        MYSQL_RES * res = mysql.query(sql);
        if (res) {
            // 若查到则返回行
            MYSQL_ROW row;
            while ((row = mysql_fetch_row(res)) != nullptr) {
                vec.emplace_back(atoi(row[0]), row[1], "", row[2]);
            }
            mysql_free_result(res);
        }
    }
    return vec;
}